<script lang="ts" setup>
import type { FormRules } from 'naive-ui'
import dayjs from 'dayjs'
import { myGoodsDetail, myGoodsList, myGoodsModify } from '@/api/goods'
import type { GoodsItemModel, MyGoodsListSendModel } from '@/api/goods'
import type { CategoryGetReturnItemModel } from '@/api/category'
import { categoryGetTwo } from '@/api/category'
import { setSku_list, setSpec_list } from '@/views/goods/set_Sku_data'
import type { SkuListItem, SpecListItem } from '@/views/goods/set_Sku_data'
import { goodsSkuGetSkuList, goodsSkuTypeDeleteSkuType, goodsSkuTypeModifySkuType } from '@/api/goodsSku'
import type { GoodsSkuGetSkuListItemModel } from '@/api/goodsSku'
import type { FileItemModel } from '@/api/file'

interface GoodsItemTableModel extends GoodsItemModel {
  sku_list?: SkuListItem[]
  spec_list?: SpecListItem[]
}
/** 初始化数据 */
const tableData = ref<GoodsItemTableModel[]>([])
const listQuery = ref<MyGoodsListSendModel>({
  page: 1,
  size: 10,
  total: 0,
})

async function getList() {
  const { code, data } = await myGoodsList(listQuery.value)
  if (code === 0) {
    tableData.value = data.list
    listQuery.value.total = data.total

    let flag = 0
    for (let i = 0; i < tableData.value.length; i++) {
      myGoodsDetail({ goodsId: tableData.value[i].id }).then(({ code, data }) => {
        if (code === 0) {
          tableData.value[i] = data
          tableData.value[i].sku_list = setSku_list(data, data.none_sku ? 'none' : '')
          tableData.value[i].spec_list = setSpec_list(data.skuList, data.none_sku ? 'none' : '')
          flag++
          if (flag === tableData.value.length)
            console.log(tableData.value, '商品数据')
        }
      })
    }
  }
}

// 获取sku大类一级分类
const skuList = ref<GoodsSkuGetSkuListItemModel[]>([])
async function getGoodsSku() {
  const { code, data } = await goodsSkuGetSkuList({ page: 1, size: 999 })
  if (code === 0)
    skuList.value = data.list
}

// 表格分类回显文字部分
const categoryTwoData = ref<CategoryGetReturnItemModel[]>()
async function getCategoryTwo() { // 获取二级分类
  const { data, code } = await categoryGetTwo()
  if (code === 0)
    categoryTwoData.value = data
}
function categoryFilter(parentId: number | string) {
  if (categoryTwoData.value?.length === 0)
    return '空'
  let categoryName = ''
  categoryTwoData.value?.forEach((item) => {
    if (item.id === parentId)
      categoryName = item.name
  })
  return categoryName
}

/** 对话框 */
interface Dialog {
  visible: boolean
  title: string
  pageType: string
  skuGroupValue: Array<string>
  goodsId: string | number
  skuId?: number | null // sku大类id
  skuItemId?: number | null // sku小类id
  name?: string // 小类规格名称
  imgId?: string | number // 规格预览图片 id
  imgList?: FileItemModel[] // 文件数据
}
const dialog = ref<Dialog>({
  visible: false,
  title: '',
  pageType: '', // 对话框类型

  skuGroupValue: [], // sku一级分类复选框组value值
  goodsId: '', // 商品id

  skuId: null, // sku大类id
  skuItemId: null, // sku小类id
  name: '', // 小类规格名称
  imgId: '', // 规格预览图片 id
  imgList: [], // 文件数据
})

interface OpenDialog {
  title?: string
  goodsId: number
  skuId?: number | null // sku大类id
  skuItemId?: number | null // sku小类id
  name?: string // 小类规格名称
  imgId?: string | number // 规格预览图片 id
  imgList?: FileItemModel[] // 文件数据
  sku?: string
}
function openDialog(pageType: string, data: OpenDialog) { // 打开对话框
  dialog.value.pageType = pageType
  dialog.value.visible = true

  switch (pageType) {
    case 'skuSelect':
      dialog.value.skuGroupValue = data.sku!.split(',').filter(item => item)
      dialog.value.goodsId = data.goodsId
      dialog.value.title = '编辑Sku分类'
      break
    case 'addSku':
      dialog.value.skuId = data.skuId
      dialog.value.goodsId = data.goodsId
      dialog.value.title = `添加规格 - ${data.title}`
      break
    case 'modefiSku':
      dialog.value.skuId = data.skuId
      dialog.value.goodsId = data.goodsId
      dialog.value.title = `修改规格 - ${data.title} - ${data.name}`
      dialog.value.skuItemId = data.skuItemId
      dialog.value.imgId = data.imgId
      dialog.value.name = data.name
      dialog.value.imgList = data.imgList
      break
  }
}
function closeDialog() { // 关闭对话框
  dialog.value = {
    visible: false,
    title: '',
    pageType: '', // 对话框类型

    skuGroupValue: [], // sku一级分类复选框组value值
    goodsId: '', // 商品id

    skuId: null, // sku大类id
    skuItemId: null, // sku小类id
    name: '', // 小类规格名称
    imgId: '', // 规格预览图片 id
    imgList: [],
  }
}
function submitDialog() { // 对话框提交
  switch (dialog.value.pageType) {
    case 'skuSelect':
      goodsModefy()
      break
    case 'addSku': case 'modefiSku':
      goodsSkuModify()
      break
  }
}
async function goodsModefy() { // 修改商品sku
  const { code, msg } = await myGoodsModify({
    id: dialog.value.goodsId,
    sku: dialog.value.skuGroupValue?.toString(),
    none_sku: dialog.value.skuGroupValue?.length === 0,
  })
  if (code === 0) {
    window.$message?.success(msg)
    closeDialog()
    getList()
  }
}
async function goodsSkuModify() { // 修改或添加sku小类规格
  const { code, msg } = await goodsSkuTypeModifySkuType({
    skuId: dialog.value.skuId as number,
    goodsId: dialog.value.goodsId as number,
    name: dialog.value.name as string,
    id: dialog.value.skuItemId ? dialog.value.skuItemId : undefined,
    imgId: dialog.value.imgId ? dialog.value.imgId : undefined,
  })
  if (code === 0) {
    window.$message?.success(msg)
    closeDialog()
    getList()
  }
}
/** 关闭tag标签回调确认 */
async function handleTagClose(id: number, key: string) {
  window.$dialog?.warning({
    title: '提示',
    content: '确定执行此操作吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      deleteSkuItem(id, key)
    },
  })
}
/** 删除sku规格小类  */
async function deleteSkuItem(id: number, key: string) {
  const { code, msg } = await goodsSkuTypeDeleteSkuType({ id, key })
  if (code === 0) {
    window.$message?.success(msg)
    getList()
  }
}
/** 表单校验 */
const rules: FormRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
}
onMounted(() => {
  getList()
  getCategoryTwo()
  getGoodsSku()
})
</script>

<template>
  <AppPage>
    <n-grid x-gap="15" :cols="8" bg-white p-10 text-14 b-rd-5 dark:bg-dark mb-20>
      <n-gi f-c-c font-bold>
        上架时间
      </n-gi>
      <n-gi f-c-c font-bold>
        商品封面
      </n-gi>
      <n-gi f-c-c font-bold>
        商品名称
      </n-gi>
      <n-gi f-c-c font-bold>
        商品标签
      </n-gi>
      <n-gi f-c-c font-bold>
        商品类别
      </n-gi>
      <n-gi f-c-c font-bold>
        商品库存
      </n-gi>
      <n-gi f-c-c font-bold>
        规格信息
      </n-gi>
      <n-gi f-c-c font-bold>
        操作
      </n-gi>
    </n-grid>
    <n-collapse>
      <n-collapse-item v-for="item in tableData" :key="item.id" :name="item.id" bg-white dark:bg-dark>
        <template #header>
          <n-grid x-gap="15" :cols="8">
            <n-gi f-c-c font-bold>
              {{ dayjs(item.createTime || new Date()).format('YYYY-MM-DD HH:mm') }}
            </n-gi>
            <n-gi f-c-c font-bold>
              <Cimage
                width="50"
                height="50"
                :src="item.iconId[0].url"
              />
            </n-gi>
            <n-gi f-c-c font-bold>
              <n-ellipsis :line-clamp="1">
                {{ item.name || '未填写' }}
              </n-ellipsis>
            </n-gi>
            <n-gi f-c-c font-bold>
              <n-tag :bordered="false">
                {{ item.hot }}
              </n-tag>
            </n-gi>
            <n-gi f-c-c font-bold>
              {{ categoryFilter(item.parentId) }}
            </n-gi>
            <n-gi f-c-c font-bold>
              {{ item.stock_num }}
            </n-gi>
            <n-gi f-c-c font-bold>
              <n-tag v-if="item.none_sku" type="error">
                无规格商品
              </n-tag>
              <n-tag v-else type="info">
                多规格商品
              </n-tag>
            </n-gi>
            <n-gi f-c-c>
              <n-button type="info" size="small" text-14 ml-5 mt5 @click.stop="openDialog('skuSelect', { goodsId: item.id, sku: item.sku })">
                <template #icon>
                  <icon-material-symbols:add />
                </template>
                编辑Sku分类
              </n-button>
            </n-gi>
          </n-grid>
        </template>
        <template #default>
          <template v-if="item.none_sku">
            <div flex items-center pb-10 ml-20 pt-10>
              无规格商品
            </div>
          </template>
          <template v-else>
            <div v-for="value in item.spec_list" :key="value.name" flex items-center pb-10 ml-20 pt-10>
              <span>{{ value.name }}: </span>
              <div v-for="v in value.list" :key="v.id" flex items-center ml-20>
                <Cimage
                  v-if="v.imgUrl"
                  width="40"
                  height="40"
                  :src="v.imgUrl[0].url"
                />
                <n-tag size="large" closable @close="handleTagClose(v.id, value.key)">
                  <span>{{ v.name }}</span>
                  <icon-mdi:square-edit-outline text-16 ml-10 cursor-pointer @click="openDialog('modefiSku', { title: value.name, name: v.name, skuId: value.id, skuItemId: v.id, imgId: v.imgUrl ? v.imgUrl[0].id.toString() : '', imgList: v.imgUrl || [], goodsId: item.id })" />
                </n-tag>
              </div>
              <n-button strong secondary type="primary" ml-20 @click="openDialog('addSku', { title: value.name, skuId: Number(value.skuId), goodsId: item.id })">
                添 加
              </n-button>
            </div>
          </template>
        </template>
      </n-collapse-item>
    </n-collapse>
    <Cpagination
      v-model:page="listQuery.page"
      :total="listQuery.total"
      :page-size="listQuery.size"
      @update-page="getList"
    />
  </AppPage>
  <Cdialog v-model:visible="dialog.visible" :title="dialog.title">
    <n-checkbox-group v-if="dialog.pageType === 'skuSelect'" v-model:value="dialog.skuGroupValue" mt-10 mb-10>
      <n-space item-style="display: flex;">
        <n-checkbox v-for="value in skuList" :key="value.id" size="large" :value="value.k_s" :label="value.k" />
      </n-space>
    </n-checkbox-group>
    <n-form
      v-if="dialog.pageType === 'addSku' || dialog.pageType === 'modefiSku'"
      ref="AddSkuDialogRef"
      size="medium"
      label-placement="top"
      :model="dialog"
      :rules="rules"
    >
      <n-alert type="warning" closable :bordered="true" mb-10>
        请在规格列表的首个列表中上传规格封面
      </n-alert>
      <n-form-item label="规格封面" path="imgId">
        <CuploadImage v-model:imageIds="dialog.imgId" :default-file-list="dialog.imgList" :max="1" width="100px" height="100px" />
      </n-form-item>
      <n-form-item label="规格名称" path="name">
        <n-input v-model:value="dialog.name" placeholder="输入规格名称" />
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space align="center" justify="center">
        <n-button b-rd-5 size="medium" @click="closeDialog">
          <n-icon cursor-pointer size="16">
            <icon-mdi:cancel />
          </n-icon>
          <span ml-2>取 消</span>
        </n-button>
        <n-button b-rd-5 type="primary" size="medium" @click="submitDialog">
          <n-icon cursor-pointer size="16">
            <icon-mdi:checkbox-marked-circle-outline />
          </n-icon>
          <span ml-2>确 定</span>
        </n-button>
      </n-space>
    </template>
  </Cdialog>
</template>

<style lang="scss" scoped>
:deep(.n-collapse-item) {
  .n-collapse-item__header{
    padding: 16px 0;
  }
}
:deep(.n-collapse .n-collapse-item:first-child > .n-collapse-item__header) {
  padding-top: 0;
}
:deep(.n-tag__content) {
  display: flex;
  align-items: center;
}
</style>
